package com.project.dao.impl;

import com.project.bean.ChannelBean;
import com.project.dao.IChannelDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 频道持久实现类
 */
@Repository
public class ChannelDaoImpl extends BaseDao implements IChannelDao {
    @Override
    public List<ChannelBean> findAll() {
        this.setConnection();
        List<ChannelBean> list = new ArrayList<>();
        try {
            ps = con.prepareStatement("SELECT c.* ,COUNT(p.`fk_channelId`) postNum  FROM t_channel c" +
                    " LEFT JOIN t_post p ON c.`pk_channelId`=p.`fk_channelId` GROUP BY c.`pk_channelId`");
            rs = ps.executeQuery();
            while (rs.next()){
                ChannelBean bean = new ChannelBean();
                bean.setId(rs.getInt("pk_channelId"));
                bean.setChannelName(rs.getString("t_name"));
                bean.setChannelContent(rs.getString("t_content"));
                bean.setPostNum(rs.getInt("postNum"));
                list.add(bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            this.closeConnection();
        }
        return list;
    }

    @Override
    public ChannelBean findById(Integer id) {
        this.setConnection();
        ChannelBean bean = null;
        try {
            ps = con.prepareStatement("SELECT c.* ,COUNT(p.`fk_channelId`) postNum  FROM t_channel c" +
                    " LEFT JOIN t_post p ON c.`pk_channelId`=p.`fk_channelId` where p.`fk_channelId`=? ");
            ps.setObject(1,id);
            rs = ps.executeQuery();
            while (rs.next()){
                 bean = new ChannelBean();
                bean.setId(rs.getInt("pk_channelId"));
                bean.setChannelName(rs.getString("t_name"));
                bean.setChannelContent(rs.getString("t_content"));
                bean.setPostNum(rs.getInt("postNum"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    public static void main(String[] args) {
        IChannelDao dao = new ChannelDaoImpl();
        System.out.println(dao.findAll());
    }
}
